// Chrome 65兼容版本 - background.js
// 移除所有ES6+语法，使用ES5语法重写

// 保存设置（使用var代替let/const）
var settings = {
  enableNotifications: true,
  enableSound: true,
  alertInterval: 5,
  soundType: 'beep'
};

// 初始化设置
chrome.runtime.onInstalled.addListener(function () {
  chrome.storage.sync.get(['enableNotifications', 'enableSound', 'alertInterval', 'soundType'], function (result) {
    var defaultSettings = {
      enableNotifications: true,
      enableSound: true,
      alertInterval: 5,
      soundType: 'beep'
    };

    // 使用传统方式更新设置，避免ES6语法
    settings.enableNotifications = (typeof result.enableNotifications !== 'undefined') ? result.enableNotifications : defaultSettings.enableNotifications;
    settings.enableSound = (typeof result.enableSound !== 'undefined') ? result.enableSound : defaultSettings.enableSound;
    settings.alertInterval = (typeof result.alertInterval !== 'undefined') ? result.alertInterval : defaultSettings.alertInterval;
    settings.soundType = (typeof result.soundType !== 'undefined') ? result.soundType : defaultSettings.soundType;

    chrome.storage.sync.set(settings);

    // 启动检查间隔
    updateCheckInterval(settings.alertInterval);
  });
});

// 监听存储变化
chrome.storage.onChanged.addListener(function (changes, namespace) {
  if (namespace === 'sync') {
    if (changes.enableNotifications) {
      settings.enableNotifications = changes.enableNotifications.newValue;
    }
    if (changes.enableSound) {
      settings.enableSound = changes.enableSound.newValue;
    }
    if (changes.alertInterval) {
      settings.alertInterval = changes.alertInterval.newValue;
      updateCheckInterval(settings.alertInterval);
    }
    if (changes.soundType) {
      settings.soundType = changes.soundType.newValue;
    }
  }
});

// 处理来自内容脚本的消息
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === 'newMessage') {
    // 存储最新消息
    chrome.storage.local.set({
      lastMessages: message.messages,
      lastMessageTime: Date.now()
    });

    // 如果启用了通知
    if (settings.enableNotifications) {
      // 通过内容脚本显示通知
      for (var i = 0; i < message.messages.length; i++) {
        var alert = message.messages[i];
        if (sender.tab && sender.tab.id) {
          chrome.tabs.sendMessage(sender.tab.id, {
            type: 'showNotification',
            title: '新预警信息 - ' + alert.unit,
            message: '电话: ' + alert.phone + '\n内容: ' + alert.content,
            alertType: 'warning',
            playSound: settings.enableSound,
            flashTitle: true,
            showOverlay: document.hidden || !document.hasFocus()
          });
        }
      }
    }
  } else if (message.type === 'settingsUpdated') {
    // 使用传统方式更新设置，避免展开运算符
    if (message.settings.enableNotifications !== undefined) {
      settings.enableNotifications = message.settings.enableNotifications;
    }
    if (message.settings.enableSound !== undefined) {
      settings.enableSound = message.settings.enableSound;
    }
    if (message.settings.alertInterval !== undefined) {
      settings.alertInterval = message.settings.alertInterval;
    }
    if (message.settings.soundType !== undefined) {
      settings.soundType = message.settings.soundType;
    }

    // 保存到存储
    chrome.storage.sync.set(settings);

    // 如果更新了检查间隔
    if (message.settings.alertInterval) {
      updateCheckInterval(message.settings.alertInterval);
    }
  } else if (message.type === 'getSettings') {
    // 发送当前设置
    sendResponse(settings);
  }
});

// 更新检查间隔
var checkIntervalId = null;

function updateCheckInterval (interval) {
  // 清除之前的间隔
  if (checkIntervalId) {
    clearInterval(checkIntervalId);
    checkIntervalId = null;
  }

  var checkInterval = interval * 60 * 1000;

  // 使用传统函数代替箭头函数，增强兼容性
  checkIntervalId = setInterval(function () {
    // 使用XMLHttpRequest代替fetch，兼容性更好
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', 'http://10.4.192.46:8080/', true);
    xhr.timeout = 3000;

    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 400) {
        // 服务器可达，发送检查消息
        chrome.tabs.query({ url: 'http://10.4.192.46:8080/*' }, function (tabs) {
          for (var i = 0; i < tabs.length; i++) {
            chrome.tabs.sendMessage(tabs[i].id, { type: 'checkNow' });
          }
        });
      }
    };

    xhr.onerror = function (error) {
      console.error('服务器不可达:', error);
    };

    xhr.ontimeout = function () {
      console.error('服务器连接超时');
    };

    xhr.send();
  }, checkInterval);
}

// 创建通知（兼容版本）
function createNotification (title, message, type) {
  // Chrome 65兼容的通知创建方式
  var notificationOptions = {
    type: 'basic',
    iconUrl: 'icons/icon48.png',
    title: title,
    message: message
  };

  // 使用chrome.notifications API（如果可用）
  if (chrome.notifications) {
    chrome.notifications.create('alert-' + Date.now(), notificationOptions, function (notificationId) {
      if (chrome.runtime.lastError) {
        console.error('通知创建失败:', chrome.runtime.lastError);
      } else {
        console.log('通知创建成功:', notificationId);
        // 5秒后清除通知
        setTimeout(function () {
          chrome.notifications.clear(notificationId);
        }, 5000);
      }
    });
  }
}

// 播放提示音（兼容版本）
function playNotificationSound () {
  // 向content script发送播放音频的消息
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'playSound',
        soundType: settings.soundType
      });
    }
  });
}

console.log('Chrome 65兼容版 background.js 已加载');